/**
 * @ClassName KP8_randtorandEqualProbability
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/10/8 15:41
 */
public class KP8_randtorandEqualProbability {

    /**
     * 1 ~ 5等概率随机
     *
     * @return
     */
    public static int rand1To5() {
        return (int) (Math.random() * 5) + 1;
    }

    /**
     * 利用rand1to5等概率随机函数生成0-1概率随机函数
     * @return
     */
    public static int rand0To1() {
        int num;
        do {
            num = rand1To5();
        }while (num == 3);
        return num < 3 ? 0 : 1;
    }

    /**
     * 利用rand01等概率随机函数制作1-7等概率随机函数
     * 利用0-1二进制等概率返回和包含0-6((1-1)-(7-1))的二进制位数，生成等概率函数，超过7的全部重做
     * @return
     */
    public static int rand1To7() {
        int ans;
        do {
            // 生成0-7之间的等概率随机数
            ans = (rand0To1() << 2) + (rand0To1() << 1) + rand0To1();
            // 把生成7的概率随机分配到其他数字生成的概率中(0-6)
        }while (ans == 7);
        return ans + 1;
    }

    public static void testRand1To5() {
        int testTimes = 1000000;
        int[] counts = new int[6];
        for (int i = 0; i < testTimes; i++) {
            int num = rand1To5();
            counts[num]++;
        }
        for (int i = 1; i < counts.length; i++) {
            System.out.println(i + "的次数：" + counts[i]);
        }
    }

    public static void testRand0To1() {
        int testTimes = 1000000;
        int[] counts = new int[2];
        for (int i = 0; i < testTimes; i++) {
            int num = rand0To1();
            counts[num]++;
        }
        for (int i = 0; i < counts.length; i++) {
            System.out.println(i + "的次数：" + counts[i]);
        }
    }

    public static void testRand1To7() {
        int testTimes = 1000000;
        int[] counts = new int[8];
        for (int i = 0; i < testTimes; i++) {
            int num = rand1To7();
            counts[num]++;
        }
        for (int i = 1; i < counts.length; i++) {
            System.out.println(i + "的次数：" + counts[i]);
        }
    }


    public static void main(String[] args) {
        //测试1-5等概率
        testRand1To5();
        System.out.println("==============");
        //测试0-1等概率
        testRand0To1();
        System.out.println("==============");
        //测试1-7等概率
        testRand1To7();
        System.out.println("==============");
    }
}
